package com.tourlaid.mamagerment.service.impl

import com.tourlaid.mamagerment.entity.User
import com.tourlaid.mamagerment.enums.TldExceptionEnum
import com.tourlaid.mamagerment.mapper.UserMapper
import com.tourlaid.mamagerment.service.UserService
import com.tourlaid.mamagerment.util.LoginUtil
import com.tourlaid.mamagerment.util.MD5Util
import com.tourlaid.mamagerment.util.TldException
import org.springframework.stereotype.Service
import java.util.*
import javax.annotation.Resource

/**
 * Created by xiaoyongge on 2017/7/21.
 */
@Service("userService")
class UserServiceImpl : UserService {

    @Resource
    val userMapper: UserMapper? = null

    override fun getByAccount(account: String?): User? {
        return userMapper!!.getByAccount(account)
    }

    override fun register(account: String?, password: String?, type: Int): Long {
        account ?: throw TldException(TldExceptionEnum.ACCOUNT_NULL)
        password ?: throw TldException(TldExceptionEnum.PASSWORD_NULL)
        var user = this.getByAccount(account)
        if (user != null) {
            throw TldException(TldExceptionEnum.ACCOUNT_EXIST)
        }
        val passwordMd5 = MD5Util.MD5Encode(password)
        user = User()
        user.account = account
        user.password = passwordMd5
        user.userType = type
        userMapper!!.insert(user)
        return user.id!!
    }

    override fun getById(id: Long): User {
        return userMapper!!.getById(id)
    }

    override fun minusIntegral() {
        val user = this.getById(LoginUtil.userId!!)
        if (Objects.equals(user.integral, 0)) throw TldException(TldExceptionEnum.INTEGRAL_LOST)
        userMapper!!.minusIntegral(LoginUtil.userId!!)
    }

    override fun plusIntegral(id: Long?, integral: Int) {
        userMapper!!.plusIntegral(id, integral, LoginUtil.userId)
    }

    override fun updateStoreId(id: Long, storeId: Long) {
        return userMapper!!.updateStoreId(id, storeId)
    }

    override fun queryByIdList(idList: List<Long>): List<User> {
        return userMapper!!.queryByIdList(idList)
    }
}